package net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP网络通信编程-服务器端
 * (字节流)
 */
public class SocketTCP02Server {

    public static void main(String[] args) throws Exception {

        /*
            编写一个服务端，和一个客户端
            服务器端在9999端口监听
            客户端连接到服务器端，发送"hello, server"，并接收服务器端回发的"hello, client"。再退出
            服务器端接收到客户端发送的信息，输出，并发送"hello,client"，再退出
         */

        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("等待客户端请求...");
        Socket socket = serverSocket.accept();
        System.out.println(socket.getClass());

        OutputStream outputStream = socket.getOutputStream();

        InputStream inputStream = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, len));
        }
        if (sb.toString().equals("hello, server")) {
            System.out.println("接收到客户端请求:" + sb);
            outputStream.write("hello, client".getBytes());
            //设置写入结束标记
            socket.shutdownOutput();
            System.out.println("服务端退出...");
            inputStream.close();
            socket.close();
            outputStream.close();
            serverSocket.close();
        }

    }
}
